package cn.ubeta.b2c.web;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.WebView;

import cn.ubeta.b2c.R;
import cn.ubeta.b2c.common.AnalyseActivity;
import cn.ubeta.b2c.common.CartCommon;
import cn.ubeta.b2c.utils.TitleBarHelper;
import cn.ubeta.b2c.widget.TitleBar;

/**
 * Created by denny on 16/9/6.
 */

public class WebViewActivity extends AnalyseActivity {

    private final static String ARG_TITLE = "title";
    private final static String ARG_URL = "url";
    private final static String ARG_IS_SHOW_CART = "isShowCart";

    private WebView mWebView;
    private boolean mIsShowCart;

    private TitleBar mTitleBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        onCreate(savedInstanceState, R.layout.activity_webview);

        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mWebView = (WebView) findViewById(R.id.web_view);

        Intent intent = getIntent();
        String title = intent.getStringExtra(ARG_TITLE);
        String url = intent.getStringExtra(ARG_URL);
        mIsShowCart = intent.getBooleanExtra(ARG_IS_SHOW_CART, false);

        if (!TextUtils.isEmpty(title)) {
            TitleBarHelper.setTitle(this, title);
        }

        mWebView.loadUrl(url);
    }

    // 购物车个数监听
    CartCommon.ICartListener mCartListener = (count, showAnimation) -> {
        if (mTitleBar != null)
            mTitleBar.refreshCartCount(count, showAnimation);
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (mIsShowCart) {
            CartCommon.addListener(mCartListener);
            mCartListener.notifyShopCartCountChanged(CartCommon.getCartCount(), false);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mIsShowCart && mCartListener != null) {
            CartCommon.removeListener(mCartListener);
        }
    }

    /**
     * 跳转到WebView
     * @param context
     * @param title
     * @param url
     * @param isShowCart
     */
    public static void gotoWebPage(Context context, String title, String url, boolean isShowCart) {
        Bundle data = new Bundle();
        data.putString(ARG_TITLE, title);
        data.putString(ARG_URL, url);
        data.putBoolean(ARG_IS_SHOW_CART, isShowCart);
        gotoActivity(context, WebViewActivity.class, data);
    }
}
